<?php
/**
 * Created by PhpStorm.
 * User: Eric-pc3
 * Date: 2018/8/2
 * Time: 18:37
 */

namespace app\common\service;

use app\common\logic\ContentLogic;
use app\common\logic\GoodsLogic;
use app\common\logic\MemberLogic;

class GoodsService extends BaseService
{
    /**
     * 分类
     * @param int $parentId 所属上级 -1 跳过 0 顶级
     * @return array
     */
    public function getGoodsCategory($parentId = -1){
        $contentLogic = new ContentLogic();
        $where[] = ['model_id','=',4];
        // TODO: 按项目搜索
        $where[] = ['project_id','=',getProjectId()];
        if ($parentId > -1) {
            $where[] = ['parent_id','=',$parentId];
        }
        $data = $contentLogic->_getCategorySelectData($where);
        return $this->retSuccess('成功', $data);
    }

    /**
     * 获取商品分页
     * @param array $postData status 状态 0 跳过（默认）； 1 出售中 ； 2 已售罄 ； 3 仓库中 ； 4 回收站；
     * @return array
     */
    public function getGoodsPager($postData = []){
        $pageIndex = 1;
        $pageSize = 20;
        // 分页
        if(!empty($postData['p'])){
            if(!is_numeric($postData['p'])){
                return $this->retError(1,'分页参数只能传数字');
            }
            $pageIndex = $postData['p'];
        }
        // 分页大小
        if(!empty($postData['size'])){
            if(!is_numeric($postData['size'])){
                return $this->retError(1,'分页大小参数只能传数字');
            }
            $pageSize = $postData['size'];
        }
        $where = [];
        // 关键词 商品名称
        if (!empty($postData['keyword'])) {
            $where[] = ['g.goods_name','LIKE','%'.$postData['keyword'].'%'];
        }

        // c 分类
        if (!empty($postData['c'])) {
            $where[] = ['g.cates','LIKE','%,'.$postData['c'].',%'];
        }

        // recommand 推荐
        if (!empty($postData['recommand'])) {
            $where[] = ['g.is_recommand','=',$postData['recommand']];
        }
        // new 新品
        if (!empty($postData['new'])) {
            $where[] = ['g.is_new','=',$postData['new']];
        }
        // hot 热销
        if (!empty($postData['hot'])) {
            $where[] = ['g.is_hot','=',$postData['hot']];
        }

        // 状态处理
        $status = 0;
        $isDel = 0;
        if (!empty($postData['status'])) {
            $status = $postData['status'];
        }
        switch ($status) {
            case 4:
                $isDel = 1;
                break;
            case 3:
                $where[] = ['g.status','=',0];
                break;
            case 2:
                $where[] = ['g.status','>',0];
                $where[] = ['g.stock','<',1];
                break;
            case 1:
                $where[] = ['g.status','>',0];
                $where[] = ['g.stock','>',0];
                break;
            default:
                break;
        }

        if($pageIndex < 1){
            $pageIndex = 1;
        }

        $goodsLogic = new GoodsLogic();

        $goodsCount = $goodsLogic->_getGoodsPagerCountByWhere($where,$isDel);

        $fanhui = [];

        // 如果查出总数 大于 0 才查列表
        if($goodsCount > 0){
            $offset = ($pageIndex - 1) * $pageSize;
            $goodsList = $goodsLogic->_getGoodsPager($where,$offset,$pageSize,'',$isDel);
            // 过滤掉不需要显示的
            foreach ($goodsList as $item) {

                $fanhui[] = [
                    'id' => $item['id'],
                    'type' => $item['type'],
                    'goods_name' => $item['goods_name'],
                    'total' => $item['stock'],
                    'minprice' => fenToYuan($item['min_price'] ? $item['min_price'] : '0'),
                    'thumb' => getGoodsThumb($item['thumbs']),
                    'has_option' => $item['has_option'],
                ];
            }
        }

        $pageInfo = [
            'has_more' => $this->_getHasMorePage($goodsCount,$pageIndex,$pageSize),
            'list' => $fanhui,
        ];

        return $this->retSuccess('成功', $pageInfo);
    }

    /**
     * 未实现推荐功能，首页推荐，目前显示全部
     * @return array
     */
    public function getRecommand(){
        $where['recommand'] = 1;
        return $this->getGoodsPager($where);
    }

    /**
     * 获取某个商品 包含扩展信息
     * @param $goodsId
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoods($goodsId){
        $goodsLogic = new GoodsLogic();
        $goodsModel = $goodsLogic->_getGoodsById($goodsId);
        if (!empty($goodsModel)) {
            // 处理 分转 元
            $goodsModel['min_price'] = fenToYuan($goodsModel['min_price']);
            $goodsModel['max_price'] = fenToYuan($goodsModel['max_price']);
            $options = $goodsModel['options'];
            foreach ($options as &$option) {
                $option['product_price'] = fenToYuan($option['product_price']);
                $option['market_price'] = fenToYuan($option['market_price']);
                $option['cost_price'] = fenToYuan($option['cost_price']);
            }
            unset($option);
            $goodsModel['options'] = $options;
        }
        return $this->retSuccess('成功', $goodsModel);
    }

    /**
     * 获取多个商品，根据多个商品ID 不含扩展信息的列表
     * @param $goodsIds
     * @return array
     */
    public function getGoodss($goodsIds){
        $goodsLogic = new GoodsLogic();
        $where[] = ['g.id','IN',$goodsIds];
        $goodsList = $goodsLogic->_getGoodsPager($where);
        return $this->retSuccess('成功', $goodsList);
    }

    public function getGoodssByCartIds($cartIds){
        if (empty($cartIds)) {
            // 没有商品ID
            return $this->retError(1,'未传参数');
        }
        if(!is_array($cartIds)){
            $ids = explode(',', $cartIds);
        }
        if (empty($ids)) {
            return $this->retError(1,'参数错误');
        }
        $goodsLogic = new GoodsLogic();
        $memberLogic = new MemberLogic();
        $cartList = $memberLogic->_getCartGoodsIdsByCartIds($ids);
        foreach ($cartList as &$item) {
            // 处理兼容性
            $item['option_id'] = $item['goods_option_id'];
            $item['cart_id'] = $item['id'];
            $item['cart_total'] = $item['total'];

            // 处理扩展信息
            $item['options'] = $goodsLogic->_getGoodsOptionListByWhere([['id','=',$item['option_id']]]);
        }

        return $this->retSuccess('成功', $cartList);
    }

    /**
     * 变更商品属性
     * @param $goodsId
     * @param $attr
     * @param $val
     * @return array
     */
    public function changeGoodsAttr($goodsId,$attr,$val){
        $allowVal = ['1','0'];
        $allowAttr = ['recommand','new','hot'];

        if (empty($goodsId)) {
            // 没有商品ID
            return $this->retError(1,'goodsId 未传参数');
        }
        if (!in_array($attr,$allowAttr)) {
            return $this->retError(1,'attr 参数不在允许范围');
        }
        if (!in_array($val,$allowVal)) {
            return $this->retError(1,'val 参数不在允许范围');
        }

        $goodsLogic = new GoodsLogic();
        $jieguo = $goodsLogic->_setGoodsAttr($goodsId, $attr, $val);
        if($jieguo === false){
            return $this->retError(1, '变更商品属性失败');
        }
        else{
            return $this->retSuccess('成功');
        }
    }
}